package com.system.cacheCenterBackend.service.cacheService;

import com.system.cacheCenterBackend.service.HashCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * Redis Hash类型缓存服务实现
 */
@Service
public class RedisHashCacheServiceImpl implements HashCacheService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void hashPut(String key, Map<String, Object> value) {
        try {
             stringRedisTemplate.opsForHash().putAll(key, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String hashGet(String key, String field) {
        try {
            Object value = stringRedisTemplate.opsForHash().get(key, field);
            return value != null ? value.toString() : null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Long hashDelete(String key, String field) {
        try {
            return stringRedisTemplate.opsForHash().delete(key, field);
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;
        }
    }

    @Override
    public Map<String, String> hashGetAll(String key) {
        try {
            Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(key);
            Map<String, String> result = new java.util.HashMap<>();
            for (Map.Entry<Object, Object> entry : entries.entrySet()) {
                result.put(entry.getKey().toString(), entry.getValue().toString());
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Boolean hashExists(String key, String field) {
        try {
            return stringRedisTemplate.opsForHash().hasKey(key, field);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Long hashSize(String key) {
        try {
            return stringRedisTemplate.opsForHash().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;
        }
    }
}